package com.tongzhou.tongzhou.message.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.tongzhou.db.DBUtil;
import com.tongzhou.db.exception.DBException;
import com.tongzhou.tongzhou.account.model.Account;
import com.tongzhou.tongzhou.message.dao.IMessageDAO;
import com.tongzhou.tongzhou.message.model.Message;
import com.tongzhou.tongzhou.message.model.SearchMessageCondition;
import com.tongzhou.util.Util;

public class MessageDAO implements IMessageDAO{

	@Override
	public int addMessage(Message message) throws DBException {
		StringBuffer sql=new StringBuffer();
		sql.append("insert into message(company_name,company_num,contact_call,content,create_time)  ");
		sql.append(" values('"+message.getCompany_name()+"','"+message.getCompany_num()+"',");
		sql.append("'"+message.getContact_call()+"','"+message.getContent()+"',now());");
		int result=DBUtil.update(sql.toString());
		return result;
	}

	@Override
	public List<Message> listMessage(SearchMessageCondition condition)
			throws DBException {
		List<Message> result=null;
		
		//查询条件SQL
		//查询参数
		StringBuffer sqlCondition = new StringBuffer() ;
		List<String> paramList = new ArrayList<String>() ;
		
		if(condition.getCompany_name() != null && !condition.getCompany_name().equals("")){
			sqlCondition.append(" and company_name like ?");
			paramList.add("%"+condition.getCompany_name()+"%");
		}
		if(condition.getCompany_num() != null && !condition.getCompany_num().equals("")){
			sqlCondition.append(" and company_num like ?") ;
			paramList.add("%"+condition.getCompany_num()+"%") ;
		}
		
		//取得满足条件的总记录数和总页数
		StringBuffer sql = new StringBuffer() ;
		sql.append("select count(id) ");
		sql.append(" from message ");
		sql.append(" where 1=1 ");
		sql.append(sqlCondition);
		
		
		//总记录数
		Map<String,String> dataMap=new HashMap<String,String>();
		long total = DBUtil.getCount(sql.toString(),paramList.toArray()) ;
		//总页数
		long totalPage = Util.getTotalPage(total, condition.getPageSize());
		
		condition.setTotal(total);
		condition.setTotalPage(totalPage);
		
		//查询某页的列表数据
		sql.delete(0, sql.length());
		sql.append("select  id,company_name,company_num,contact_call,content,create_time ");
		sql.append(" from message ");
		sql.append(" where 1=1 ");
		sql.append(sqlCondition);
		sql.append(" order by "+condition.getOrderBy()+" "+condition.getOrderByType()) ;
		result = DBUtil.query(sql.toString(), new BeanListHandler<Message>(Message.class), paramList.toArray(), Util.getStartPos(condition.getCurrentPage(), condition.getPageSize()), condition.getPageSize()) ;
		return result;
	}

}
